package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.RequestContextUtil;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.dto.WmNewsContentNodeDto;
import com.itheima.wemedia.feign.WmMaterialFeign;
import com.itheima.wemedia.pojo.WmMaterial;
import com.itheima.wemedia.pojo.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @description 上传文件的服务
 * @package com.itheima.dfs
 */
@RestController
@RequestMapping("/dfs")
@Slf4j
public class FileController {

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private WmMaterialFeign wmMaterialFeign;

    /**
     * 上传文件
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    public ResultVo upload(MultipartFile multipartFile) {
        // 请求来源鉴权
        String from = RequestContextUtil.getHeader(SystemConstants.USER_HEADER_FROM);
        if (!"wemedia-pic".equals(from)) {
            throw new LeadNewsException("非法参数!");
        }
        //1. 上传文件到fastdfs
        try {
            StorePath storePath = client.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(),
                    StringUtils.getFilenameExtension(multipartFile.getOriginalFilename()), null);
            //2. 拼接文件的完整路径
            String url = fdfsWebServer.getWebServerUrl()+ storePath.getFullPath();
            log.debug("上传文件url:{}",url);
            log.debug("下载/储存图片地址:{}",storePath.getFullPath());
            // 构建素材pojo
            WmMaterial material = new WmMaterial();
            //不保存全路径
//            material.setUrl(url);
            material.setUrl(storePath.getFullPath());
            // 填充其它属性值
            // 当前登录的自媒体用户Id
            material.setUserId(Integer.parseInt(RequestContextUtil.getUserId()));
            material.setIsCollection(0);
            material.setType(0);//素材类型 0:图片
            material.setCreatedTime(LocalDateTime.now());
            //远程调用添加素材
            ResultVo<WmMaterial> result = wmMaterialFeign.insert(material);
            if(!result.isSuccess()){
                log.error("添加素材远程调用失败 url={}",url);
                return ResultVo.bizError("上传素材失败");
            }
            //3. 返回文件路径
            ResultVo resultVo = ResultVo.ok(Collections.singletonMap("url", url));
            //回显图片
//            resultVo.setHost(fdfsWebServer.getWebServerUrl());
            return resultVo;

        } catch (IOException e) {
            log.error("上传文件失败", e);
        }
        return ResultVo.error();
    }
    @PostMapping("/download")
    public ResultVo<List<byte[]>> download(@RequestBody List<String> imageList){
        System.out.println("请求来了"+imageList);
        List<byte[]> resultList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(imageList)){
            DownloadByteArray downloadByteArray = new DownloadByteArray();
            for (String imageUrl : imageList) {
                //p1: group分组,p2: 文件路径, p3:指定返回类型
                StorePath storePath = StorePath.parseFromUrl(imageUrl);
                String group = storePath.getGroup();
                String path = storePath.getPath();
//                下载文件为字节数组
                byte[] bytes = client.downloadFile(group,path,downloadByteArray);
                resultList.add(bytes);
            }
        }
        return ResultVo.ok(resultList);
    }


}
